package auth

import (
	"errors"

	"github.com/gin-gonic/gin"

	"hyper/app/Models"
	"hyper/supports/jwt"
)

// 用户登录
func Attempt(username string, password string) (Models.User, error) {
	// 根据用户名获取用户
	_user := Models.IsUserExist(username)

	// 2. 如果出现错误
	if _user.ID == 0 {
		return Models.User{}, errors.New("用户名或密码错误！")
	}

	// 密码错误
	if !_user.ComparePassword(password) {
		return Models.User{}, errors.New("用户名或密码错误！")
	}

	return _user, nil
}

// 用户信息获取
func Auth(attributes string, c *gin.Context) (interface{}, error) {
	user, _ := jwt.GetTokenFromHeader(c)

	payload, err := jwt.ParseToken(user)

	data, bool := payload["data"].(map[string]interface{})

	if bool && attributes != "" {
		return data[attributes], err
	} else {
		return data, err
	}

}
